<template v-if="visible">
  <basic-container v-loading="importConfig.fileLoading" :element-loading-text="importConfig.fileLoadingText" element-loading-spinner="el-icon-loading">
    <el-row>
      <el-col class="configData" :span="12">
        <avue-crud
          :option="option"
          :table-loading="loading"
          :data="data"
          :page.sync="page"
          :permission="permissionList"
          :before-open="beforeOpen"
          v-model="form"
          ref="crud"
          @row-update="rowUpdate"
          @row-save="rowSave"
          @row-click="onClick"
          @search-change="searchChange"
          @search-reset="searchReset"
          @selection-change="selectionChange"
          @current-change="currentChange"
          @size-change="sizeChange"
          @refresh-change="refreshChange"
          @on-load="onLoad"
        >
          <template slot-scope="{ row }" slot="isMultiline">
            <el-tag :class="row.isMultiline ? 'successTag' : 'dangerTag'">{{ row.isMultiline ? '是' : '否' }}</el-tag>
          </template>
          <template slot="menuLeft">
            <el-button type="primary" size="small" icon="el-icon-plus" v-if="permission.excelimportconfig_add" @click="addBtn">新 增</el-button>
            <el-button type="danger" size="small" icon="el-icon-delete" v-if="permission.excelimportconfig_delete" @click="handleDelete">删 除</el-button>
            <el-button type="success" size="small" icon="el-icon-upload2" v-if="permission.excelimportconfig_upload" @click="handleImport">导 入</el-button>
            <el-button type="warning" size="small" plain icon="el-icon-download" @click="handleExport">导出 </el-button>
            <el-button type="success" size="small" icon="el-icon-download" v-if="permission.excelimportconfig_downLoad" @click="handleDownload">下 载</el-button>
          </template>
          <template slot-scope="{ row }" slot="menu">
            <el-button icon="el-icon-view" size="small" type="text" v-if="permission.excelimportconfig_view" @click.stop="rowView(row)">查看</el-button>
            <el-button icon="el-icon-edit" size="small" type="text" v-if="permission.excelimportconfig_edit" @click.stop="rowUpdate(row)">编辑</el-button>
            <el-button icon="el-icon-delete" size="small" type="text" v-if="permission.excelimportconfig_delete" @click.stop="rowDel(row, 1)">删除</el-button>
          </template>
        </avue-crud>
      </el-col>
      <el-col :span="12" style="padding: 10px">
        <el-tabs class="detailTable" type="border-card" v-if="isShowDetailTable">
          <el-tab-pane label="EXCEL导入配置详情">
            <avue-crud
              class="detailTable"
              :table-loading="detailLoading"
              :before-open="detailBeforeOpen"
              :before-close="detailBeforeClose"
              :page.sync="detailPage"
              v-model="detailForm"
              ref="detailCrud"
              v-bind="bindVal"
              v-on="onEvent"
            >
              <template slot-scope="{ row }" slot="isMultiline">
                <el-tag :class="row.isMultiline ? 'successTag' : 'dangerTag'">{{ row.isMultiline ? '是' : '否' }}</el-tag>
              </template>
              <template slot="menuLeft">
                <el-button type="primary" size="small" icon="el-icon-plus" @click="addDetailBtn" v-if="parentId && permission.excelimportconfig_add">新增 </el-button>
                <el-button type="danger" size="small" icon="el-icon-delete" @click="handleDetailDelete" v-if="parentId && permission.excelimportconfig_delete">删 除 </el-button>
                <el-button type="warning" size="small" plain icon="el-icon-download" v-if="parentId" @click="handleExport">导出 </el-button>
              </template>
              <template slot-scope="{ row }" slot="menu">
                <el-button icon="el-icon-view" size="small" type="text" v-if="permission.excelimportconfig_view" @click="rowDetailView(row)">查看</el-button>
                <el-button icon="el-icon-edit" size="small" type="text" v-if="permission.excelimportconfig_edit" @click="rowDetailUpdate(row)">编辑</el-button>
                <el-button icon="el-icon-delete" size="small" type="text" v-if="permission.excelimportconfig_delete" @click="rowDel(row, 2)">删除</el-button>
              </template>
            </avue-crud>
          </el-tab-pane>
        </el-tabs>
      </el-col>
    </el-row>
    <el-dialog
      ref="dialog"
      width="50%"
      :title="dialogTitle"
      :key="timer"
      append-to-body
      :visible.sync="showDialog"
      v-if="showDialog"
      @close="closeDialog"
      top="5vh"
      destroy-on-close
    >
      <el-tabs v-model="tabsIndex" type="card" @tab-click="handleChange" v-loading="dialogLoading">
        <el-tab-pane label="基础数据" name="1">
          <avue-form ref="basicForm" v-model="model" key="basicForm" :option="basicOptions">
            <template slot="primaryKeys">
              <el-input v-model="model.primaryKeys" placeholder="请输入主键">
                <el-button slot="append" icon="el-icon-plus" @click="addKeyEvent(model.primaryKeys)"></el-button>
              </el-input>
              <div>
                <ul style="margin: 0;position">
                  <li class="list-item" v-for="(item, index) in model.excelImportPrimaryList" :key="index">
                    {{ item.primaryKey }} <i class="el-icon-circle-close" @click="clearEvent(index)"></i>
                  </li>
                </ul>
              </div>
            </template>
          </avue-form>
        </el-tab-pane>

        <el-tab-pane label="读取字段配置" name="2">
          <div class="top-title-flex">
            <i class="el-icon-download top-title-flex">请添加输入字段名称</i>
            <div class="top-title-flex">
              <el-button icon="el-icon-plus" size="small" type="primary" @click="addDataReadRow()" v-if="!dialogTitle.includes('查看')">新增</el-button>
              <el-button
                icon="el-icon-edit"
                size="small"
                type="primary"
                @click="editDataReadRow"
                :disabled="!basicModel.code || readDataMap.length === 0"
                v-if="!dialogTitle.includes('查看')"
                >编辑</el-button
              >
              <el-button
                class="el-button el-button--danger el-button--small is-plain"
                @click="onHandleWordDelete()"
                size="small"
                type="danger"
                v-if="!dialogTitle.includes('查看')"
                :disabled="readDataMap.length === 0 || !basicModel.code"
                ><i class="el-icon-delete"></i>删除</el-button
              >
            </div>
          </div>
          <avue-crud
            ref="readPropertiesCrud"
            @mousewheel.native="handleMouseWheel"
            :data="readDataMap"
            :option="readPropertiesCrudOptions"
            @cell-click="onHandleWordSelect"
            @row-click="onReadClick"
            v-model="model"
          ></avue-crud>

          <el-dialog
            width="30%"
            :title="fieldDialogConfig.title"
            :visible.sync="fieldDialogConfig.visible"
            top="5vh"
            close-on-press-escape
            :close-on-click-modal="false"
            append-to-body
            @open="openBasicInfoFormDialog"
          >
            <avue-form ref="basicInfoForm" v-model="basicModel" key="basicInfoForm" :option="basicInfoOptions"> </avue-form>
            <div v-if="dialogInnerTitle != '查看'" slot="footer" class="dialog-footer">
              <el-button type="primary" size="small" icon="el-icon-circle-plus-outline" @click="submitInner">保存</el-button>
              <el-button size="small" icon="el-icon-circle-close" @click="cancelEvent">取消</el-button>
            </div>
          </el-dialog>
        </el-tab-pane>

        <el-tab-pane label="执行后SQL" name="3">
          <div class="top-title-flex">
            <i class="el-icon-download top-title-flex">请添加输入字段名称(双击确认)</i>
            <div class="top-title-flex">
              <el-button icon="el-icon-plus" size="small" type="primary" @click="addDataSourceRow('AfterPropertiesCrud')" v-if="!dialogTitle.includes('查看')">新增</el-button>
              <el-button
                class="el-button el-button--danger el-button--small is-plain"
                size="small"
                @click="onHandleDelete()"
                type="danger"
                v-if="!dialogTitle.includes('查看')"
                :disabled="dataAfterMap.length === 0"
                ><i class="el-icon-delete"></i>删除</el-button
              >
            </div>
          </div>
          <avue-crud
            ref="AfterPropertiesCrud"
            v-model="model"
            :data="dataAfterMap"
            :option="AfterPropertiesOption"
            @cell-click="onHandleAfterSelect"
            @row-dblclick="handleRowClick"
          ></avue-crud
        ></el-tab-pane>
      </el-tabs>

      <div v-if="!dialogTitle.includes('查看')" slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" icon="el-icon-circle-plus-outline" @click="submit">保存</el-button>
        <el-button size="small" icon="el-icon-circle-close" @click="closeDialog">取消</el-button>
      </div>
    </el-dialog>

    <!-- 导入 -->
    <el-dialog title="导入" :visible.sync="importConfig.open" width="50%" append-to-body @open="importConfigOpen" :close-on-click-modal="false" :close-on-press-escape="false">
      <avue-form ref="importConfigForm" v-model="importForm" :option="importConfig.option">
        <template slot="imgUrl">
          <el-upload
            ref="excelFile"
            class="importConfigDialog"
            drag
            action="#"
            accept=".xlsx,.xls"
            limit="1"
            :auto-upload="false"
            :before-remove="handleBeforeRemove"
            :on-change="changeFile"
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip" slot="tip">仅限拓展名为.xlsx,.xls的文件</div>
          </el-upload>
        </template>
      </avue-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-preventReClick type="primary" size="small" @click="saveImport" icon="el-icon-circle-plus-outline">保 存</el-button>
        <el-button @click="cancelImport" size="small" icon="el-icon-circle-close">取 消</el-button>
      </div>
    </el-dialog>
    <export-excel
      :visible="exprotVisible"
      :option="option"
      :page="page"
      :data="exportData"
      name="excel导入配置"
      :loading="btnLoading"
      @selectData="handleSelectData"
      @close="handleClose"
    ></export-excel>
  </basic-container>
</template>

<script>
import { getList, getDetail, add, update, remove, getExcelTemplate, excelImport } from '@/api/admin/excelimportconfig';
import { downloadExcel } from '@/util/util';
import { mapGetters } from 'vuex';
import { deepClone } from '@/util/util';
import { getToken } from '@/util/auth';
import exportExcel from '@/components/export-excel';
export default {
  name: 'AdminExcelimportconfig',
  components: {
    exportExcel
  },
  data() {
    const validateRowIndex = (rule, value, callback) => {
      let reg = /(^[1-9]\d*$)/;
      if (value && value != '0') {
        if (!reg.test(value)) {
          callback(new Error('请输入正确的数字格式'));
        }
      }
      callback();
    };
    const obj = {
      height: 'calc(100vh - 370px)',
      calcHeight: 30,
      tip: false,
      searchShow: true,
      searchMenuSpan: 8,
      searchSpan: 8,
      border: true,
      index: true,
      editBtn: false,
      delBtn: false,
      viewBtn: false,
      selection: true,
      dialogClickModal: false,
      addBtn: false,
      indexLabel: '序号'
    };
    const optionObj = [
      {
        label: this.$t('code'),
        prop: 'code',
        span: 24,
        labelWidth: 150,
        search: true,
        rules: [
          {
            required: true,
            message: '请输入编码',
            trigger: 'blur'
          }
        ]
      },
      {
        label: this.$t('sequence'),
        prop: 'sequence',
        span: 24,
        type: 'number',
        minRows: 0,
        labelWidth: 150,
        hide: true,
        rules: [
          {
            required: true,
            message: '请输入顺序',
            trigger: 'change'
          }
        ]
      },
      {
        label: this.$t('getSheetMode'),
        prop: 'getSheetMode',
        span: 24,
        labelWidth: 150,
        type: 'radio',
        value: 'NAME',
        dicData: [
          {
            label: '名称',
            value: 'NAME'
          },
          {
            label: '索引',
            value: 'INDEX'
          }
        ],
        control: (val, form) => {
          if (val == 'NAME') {
            return {
              sheetName: { display: true },
              sheetIndex: { display: false }
            };
          } else if (val == 'INDEX') {
            return {
              sheetIndex: { display: true },
              sheetName: { display: false }
            };
          }
        },
        hide: true,
        rules: [
          {
            required: true,
            message: '请输入获取sheet方式',
            trigger: 'blur'
          }
        ]
      },
      {
        label: 'sheet名',
        prop: 'sheetName',
        span: 24,
        labelWidth: 150,
        hide: true,
        display: false,
        rules: [
          {
            required: true,
            message: '请输入sheet名',
            trigger: 'blur'
          }
        ]
      },
      {
        label: 'sheet索引',
        prop: 'sheetIndex',
        span: 24,
        labelWidth: 150,
        hide: true,
        display: false,
        rules: [
          {
            required: true,
            message: '请输入sheet索引',
            trigger: 'blur'
          }
        ]
      },
      {
        label: this.$t('isMultipleLine'),
        prop: 'isMultiline',
        labelWidth: 150,
        span: 24,
        type: 'switch',
        value: false,
        dicData: [
          {
            label: '否',
            value: false
          },
          {
            label: '是',
            value: true
          }
        ],
        control: (val, form) => {
          if (val == true) {
            return {
              startRowIndex: { display: true },
              endColumnIndex: { display: true },
              endRegularExpression: { display: true }
            };
          } else {
            delete this.model.startRowIndex;
            delete this.model.endColumnIndex;
            delete this.model.endRegularExpression;
            return {
              startRowIndex: { display: false },
              endColumnIndex: { display: false },
              endRegularExpression: { display: false }
            };
          }
        }
      },
      {
        label: this.$t('startRowIndex'),
        prop: 'startRowIndex',
        span: 24,
        labelWidth: 150,
        hide: true,
        rules: [
          {
            required: true,
            message: '请输入开始读取行索引',
            trigger: 'blur'
          }
        ]
      },
      {
        label: this.$t('endColumnIndex'),
        prop: 'endColumnIndex',
        span: 24,
        labelWidth: 150,
        hide: true,
        rules: [
          {
            required: true,
            message: '请输入结束标识列索引',
            trigger: 'blur'
          }
        ]
      },
      {
        label: this.$t('endRegularExpression'),
        prop: 'endRegularExpression',
        span: 24,
        labelWidth: 150,
        hide: true
      },
      {
        label: '表名称',
        prop: 'tableName',
        span: 24,
        labelWidth: 150,
        search: true,
        rules: [
          {
            required: true,
            message: '请输入表名称',
            trigger: 'blur'
          }
        ]
      },
      {
        label: this.$t('hasTitle'),
        prop: 'hasTitle',
        span: 24,
        labelWidth: 150,
        hide: true,
        value: false,
        type: 'switch',
        dicData: [
          {
            value: false
          },
          {
            value: true
          }
        ],
        control: (val, form) => {
          if (val == true) {
            // this.model.titleRowIndex = '';
            return {
              titleRowIndex: { display: true }
            };
          } else {
            delete this.model.titleRowIndex;
            return {
              titleRowIndex: { display: false }
            };
          }
        }
      },
      {
        label: this.$t('titleRowIndex'),
        prop: 'titleRowIndex',
        type: 'number',
        span: 24,
        labelWidth: 150,
        hide: true,
        rules: [
          {
            required: true,
            message: '请输入标题行索引',
            trigger: 'blur'
          }
        ]
      },
      {
        label: '主键',
        span: 24,
        labelWidth: 150,
        prop: 'primaryKeys',
        formslot: true,
        hide: true
      },
      // {
      //   label: '备注',
      //   span: 24,
      //   labelWidth: 150,
      //   type: 'textarea',
      //   prop: 'remark',
      //   hide: true,
      //   minRows: 3
      // }
      {
        label: '导入后执行脚本',
        span: 24,
        labelWidth: 150,
        prop: 'afterSql',
        hide: true
      }
    ];

    const optionsRead = [
      {
        label: '名称',
        prop: 'columnName',
        span: 24,
        labelWidth: 150,
        rules: [
          {
            required: true,
            message: '请输入名称',
            trigger: 'blur'
          }
        ]
      },
      {
        label: '编码',
        prop: 'code',
        span: 24,
        width: 50,
        labelWidth: 150,
        cell: true,
        rules: [
          {
            required: true,
            message: '请输入编码',
            trigger: 'blur'
          }
        ]
      },
      {
        label: '获取sheet类别',
        prop: 'getSheetMode',
        type: 'radio',
        span: 24,
        labelWidth: 150,
        width: 100,
        rules: [
          {
            required: true,
            message: '请选择sheet类别'
          }
        ],
        value: 'NAME',
        dicData: [
          {
            label: '名称',
            value: 'NAME'
          },
          {
            label: '索引',
            value: 'INDEX'
          }
        ],
        control: (val, form) => {
          if (val == 'NAME') {
            return {
              sheetName: { display: true },
              sheetIndex: { display: false }
            };
          } else if (val == 'INDEX') {
            return {
              sheetIndex: { display: true },
              sheetName: { display: false }
            };
          }
        }
      },
      {
        label: 'sheet名称',
        prop: 'sheetName',
        span: 24,
        labelWidth: 150,
        display: false,
        rules: [
          {
            required: true,
            message: '请输入sheet名称'
          }
        ]
      },
      {
        label: 'sheet索引',
        display: false,
        prop: 'sheetIndex',
        type: 'number',
        controls: false,
        span: 24,
        labelWidth: 150,
        rules: [
          {
            required: true,
            message: '请输入sheet索引',
            trigger: 'blur'
          }
        ]
      },
      {
        label: '是否固定行索引',
        prop: 'isFixRowIndex',
        span: 24,
        labelWidth: 150,
        width: 110,
        type: 'switch',
        dicData: [
          {
            value: 'false'
          },
          {
            value: 'true'
          }
        ]
      },
      {
        label: '行索引',
        prop: 'rowIndex',
        controls: false,
        span: 24,
        width: 70,
        labelWidth: 150,
        rules: [{ validator: validateRowIndex, trigger: 'blur' }]
      },
      {
        label: '获取列类别',
        prop: 'getColumnMode',
        span: 24,
        labelWidth: 150,
        width: 80,
        rules: [
          {
            required: true,
            message: '请输入sheet索引',
            trigger: 'blur'
          }
        ],
        type: 'radio',
        value: 'NAME',
        dicData: [
          {
            label: '名称',
            value: 'NAME'
          },
          {
            label: '索引',
            value: 'INDEX'
          }
        ],
        control: (val, form) => {
          if (val == 'NAME') {
            return {
              readColumnIndex: { display: false },
              readColumnName: { display: true }
            };
          } else if (val == 'INDEX') {
            return {
              readColumnIndex: { display: true },
              readColumnName: { display: false }
            };
          }
        }
      },
      {
        label: 'Excel列索引',
        prop: 'readColumnIndex',
        type: 'number',
        controls: false,
        display: false,
        span: 24,
        width: 90,
        labelWidth: 150,
        rules: [
          {
            required: true,
            message: '请输入Excel列索引',
            trigger: 'blur'
          }
        ]
      },
      {
        label: 'Excel列名称',
        prop: 'readColumnName',
        span: 24,
        display: false,
        width: 90,
        labelWidth: 150,
        rules: [
          {
            required: true,
            message: '请输入Excel列名称',
            trigger: 'blur'
          }
        ]
      },
      {
        label: '提取正则',
        prop: 'readRegex',
        span: 24,
        labelWidth: 150
      },
      {
        label: '默认值',
        prop: 'defaultValue',
        span: 24,
        labelWidth: 150
      }
      // {
      //   label: '是否启用',
      //   prop: 'isuse',
      //   span: 24,
      //   labelWidth: 150,
      //   type: 'switch',
      //   dicData: [
      //     {
      //       value: 'false'
      //     },
      //     {
      //       value: 'true'
      //     }
      //   ]
      // }
    ];
    return {
      importForm: {
        imgUrl: {}
      },
      exprotVisible: false,
      btnLoading: false,
      exportData: [],
      importConfig: {
        open: false,
        fileLoading: false,
        fileLoadingText: '文件下载中，请稍后...',
        option: {
          emptyBtn: false,
          submitBtn: false,
          column: [
            {
              label: '文件上传',
              prop: 'imgUrl',
              type: 'upload',
              loadText: '文件上传中，请稍等',
              span: 24,
              propsHttp: {
                res: 'data'
              },
              data: {},
              headers: {
                'Blade-Auth': getToken()
              },
              tip: '只能上传拓展名为.xlsx,.xls的文件',
              action: '#'
            }
          ]
        }
      },
      // 读取字段配置弹窗
      fieldDialogConfig: {
        title: '添加字段配置',
        visible: false
      },
      dialogLoading: false,
      showDialog: false,
      dialogTitle: '新增',
      dialogInnerTitle: '新增',
      readDataMap: [],
      dataAfterMap: [], //执行后sql
      form: {},
      query: {},
      model: {},
      basicModel: {},
      tabsIndex: '1',
      index: 1,
      loading: true,
      type: '',
      leftTableFlag: '',
      parentId: '',
      timer: new Date().getTime(),
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      detailPage: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      // primaryKeyArr: [],
      selectionList: [],
      type: {
        icon: 'el-icon-info',
        label: '基础数据',
        prop: 'tab1'
      },
      //基础数据配置
      basicOptions: {
        submitBtn: false,
        emptyBtn: false,
        editBtn: false,
        column: [...optionObj]
      },
      //tab选项卡显示
      tabOptions: {
        column: [
          {
            icon: 'el-icon-info',
            label: '基础数据',
            prop: 'tab1'
          },
          {
            icon: 'el-icon-info',
            label: '读取字段配置',
            prop: 'tab2'
          },
          {
            icon: 'el-icon-info',
            label: '执行后SQL',
            prop: 'tab3'
          }
        ]
      },
      //列表显示
      option: {
        ...obj,
        highlightCurrentRow: true, // 选中高亮
        column: [...optionObj]
      },
      //详情配置
      detailOption: {
        ...obj,
        column: [
          // {
          //   label: '名称',
          //   prop: 'name',
          //   search: true,
          // },
          {
            label: '编码',
            prop: 'code'
          },
          {
            label: '表名称',
            prop: 'tableName'
          },
          {
            label: '是否多项',
            prop: 'isMultiline'
          }
        ]
      },
      // 读取字段配置信息
      readPropertiesCrudOptions: {
        height: '500',
        border: true,
        index: true,
        editBtn: false,
        delBtn: false,
        viewBtn: false,
        dialogClickModal: false,
        menu: false,
        menuWidth: 150,
        addBtn: false, //添加按钮
        refreshBtn: false, //刷新按钮是否显示
        columnBtn: false, //控制表格列是否显示按钮是否显示
        highlightCurrentRow: true,
        column: [...optionsRead]
      },
      basicInfoOptions: {
        submitBtn: false,
        emptyBtn: false,
        column: [...optionsRead]
      },
      //执行后sql
      AfterPropertiesOption: {
        height: '500',
        border: true,
        menu: false,
        index: true,
        addBtn: false,
        refreshBtn: false,
        columnBtn: false,
        addRowBtn: false,
        cellBtn: true,
        indexLabel: '序号',
        highlightCurrentRow: true, // 选中高亮
        column: [
          {
            label: '执行后SQL',
            prop: 'afterSql',
            cell: true //编辑的字段设置cell为true
          }
        ]
      },
      detailLoading: false,
      data: [],
      detailData: [],
      visible: true,
      isFirst: true,
      // sql下标
      afterIndex: -1,
      wordIndex: -1,
      isShowDetailTable: false
    };
  },
  inject: ['globalStartLoad', 'globalEndLoad'],
  computed: {
    ...mapGetters(['permission']),

    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.excelimportconfig_add, false),
        viewBtn: this.vaildData(this.permission.excelimportconfig_view, false),
        delBtn: this.vaildData(this.permission.excelimportconfig_delete, false),
        editBtn: this.vaildData(this.permission.excelimportconfig_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    },
    onEvent() {
      return {
        // 'on-load': this.getList,
        'row-save': this.rowSave,
        // 'row-update': this.rowUpdate,
        'row-del': this.rowDel,
        'refresh-change': this.refreshDetailChange
        // 'search-reset': this.searchReset,
        // 'search-change': this.searchChange
      };
    },

    bindVal() {
      return {
        ref: 'detailCrud',
        option: this.detailOption,
        data: this.detailData,
        tableLoading: this.detailLoading
      };
    }
  },
  mounted() {
    // this.resetHeightHandler();
    this.$nextTick(() => {
      //搜索与表格结构分隔
      this.$structuralSplit();
      this.isShowDetailTable = true;
    });
  },
  // beforeDestroy() {
  //   window.removeEventListener('resize', this.resetHeight);
  // },
  methods: {
    importConfigOpen() {
      for (const key in this.importForm) {
        this.importForm.imgUrl = {};
      }
      this.$nextTick(() => {
        this.$refs.excelFile.clearFiles();
      });
    },
    // 导入
    handleImport() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      if (this.selectionList.length > 1) {
        this.$message.warning('此操作只允许选择一条数据');
        return;
      }
      this.importConfig.open = true;
    },
    async handleBeforeRemove(file, fileList) {
      let res = await this.$confirm(`确定移除 ${file.name}？`, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      });
      if (res) {
        this.importForm.imgUrl = {};
        this.$message({
          type: 'success',
          message: '移除成功!'
        });
      }
    },
    changeFile(val) {
      let nameArray = val.name.split('.');
      if (nameArray[nameArray.length - 1] === 'xlsx' || nameArray[nameArray.length - 1] === 'xls') {
        // file保存选择的文件
        this.importForm.imgUrl = val.raw;
      } else {
        this.$message({
          message: '文件格式错误,请确认文件内容并重新上传',
          type: 'warning',
          duration: 2000
        });
      }
    },
    saveImport() {
      if (Object.keys(this.importForm.imgUrl).length == 0) {
        this.$message.warning('请先上传文件后再操作！');
        return;
      }
      const file = this.importForm.imgUrl;
      let fileParams = new FormData();
      fileParams.append('file', file);
      excelImport(this.ids, fileParams)
        .then((res) => {
          this.importConfig.open = false;
          this.$message.success(res.data.msg);
        })
        .catch(() => {});
    },
    cancelImport() {
      this.importConfig.open = false;
    },
    addBtn() {
      this.showDialog = true;
      this.model.excelImportPrimaryList = [];
      this.model.id = '';
      this.tabsIndex = '1';
      this.leftTableFlag = true;
      this.dialogTitle = '新增导入信息';
      this.resetForm();
    },

    addDetailBtn() {
      this.showDialog = true;
      this.model.excelImportPrimaryList = [];
      this.tabsIndex = '1';
      this.leftTableFlag = false;
      this.dialogTitle = '新增表信息';
      this.resetForm();
    },

    /**
     * 新增sql
     */
    addDataSourceRow(titleVal) {
      this.$refs[titleVal].rowCellAdd({
        cell: true
      });
    },

    addDataReadRow() {
      this.type = 'add';
      this.fieldDialogConfig.title = '添加字段配置';
      this.fieldDialogConfig.visible = true;
    },

    editDataReadRow() {
      if (!this.basicModel.code) {
        this.$message({
          type: 'warning',
          message: '请先选择一条数据'
        });
        return;
      }

      console.log('this.basicModel', this.basicModel);
      this.type = 'edit';
      this.fieldDialogConfig.title = '编辑字段配置';
      this.fieldDialogConfig.visible = true;
    },

    /**
     * 选中单前行
     */
    onHandleAfterSelect(row) {
      // if (!row) return;
      // this.afterIndex = row.$index;
      // this.$refs.AfterPropertiesCrud.setCurrentRow(row);
    },

    onHandleWordSelect(row) {
      if (!row) return;
      this.wordIndex = row.$index;
      this.$refs.readPropertiesCrud.setCurrentRow(row);
    },

    onReadClick(row) {
      this.index = row.$index;
      this.basicModel = row;
    },

    /**
     * 鼠标滚动的时候 让横向滚动自己滚
     */
    handleMouseWheel(e) {
      let scrollLeft = document.getElementsByClassName('el-table__body-wrapper')[2].scrollLeft;
      let offsetWidth = document.getElementsByClassName('el-table__body-wrapper')[2].offsetWidth;
      let scrollWidth = document.getElementsByClassName('el-table__body-wrapper')[2].scrollWidth;
      if (e.wheelDelta > 0 && scrollLeft + offsetWidth <= scrollWidth) {
        document.getElementsByClassName('el-table__body-wrapper')[2].scrollLeft += 20;
      } else if (e.wheelDelta < 0 && scrollLeft > 0) {
        document.getElementsByClassName('el-table__body-wrapper')[2].scrollLeft -= 20;
      }
    },

    /**
     * 双击当前行
     */
    handleRowClick(row, column) {
      if (!row) return;
      if ('afterSqlStrings'.includes(column.property)) {
        row.$cellEdit == true ? (row.$cellEdit = false) : this.$refs.AfterPropertiesCrud.rowCell(row, row.$index);
      }
    },

    rowSave(row, done, loading) {
      add(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        },
        (error) => {
          loading();
          window.console.log(error);
        }
      );
    },

    rowView(row) {
      this.showDialog = true;
      this.dialogTitle = '查看导入信息';
      this.leftTableFlag = true;
      this.dialogLoading = true;
      this.getDetailInfo(row);
    },

    rowDetailView(row) {
      this.showDialog = true;
      this.dialogTitle = '查看表信息';
      this.leftTableFlag = false;
      this.dialogLoading = true;
      this.getDetailInfo(row);
    },

    rowUpdate(row) {
      this.showDialog = true;
      this.tabsIndex = '1';
      this.dialogTitle = '编辑导入信息';
      this.leftTableFlag = true;
      this.dialogLoading = true;
      this.getDetailInfo(row);
    },

    rowDetailUpdate(row) {
      this.showDialog = true;
      this.dialogTitle = '编辑表信息';
      this.leftTableFlag = false;
      this.dialogLoading = true;
      this.getDetailInfo(row);
    },

    async getDetailInfo(row) {
      let params = {
        id: row.id
      };
      if (!this.leftTableFlag) {
        params.parentId = this.parentId;
      }
      const { data: res } = await getDetail(params);
      if (res.code != 200) {
        this.$message({
          type: 'warning',
          message: `暂未获取到数据`
        });
        return;
      }
      this.model = res.data;
      this.dataAfterMap = res.data.excelImportAfterSqlList;
      this.readDataMap = res.data.excelImportFieldList || [];
      this.dialogLoading = false;
    },

    rowDel(row, type) {
      const that = this;
      that
        .$confirm('确定将选择数据删除?', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          if (type == 2) {
            that.onDetailLoad(that.detailPage, {
              parentId: that.parentId
            });
          }
          if (type == 1) {
            this.query.parentId = 0;
            this.onLoad(that.page);
          }
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        });
    },
    handleDetailDelete() {},
    // 下载
    handleDownload() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      if (this.selectionList.length > 1) {
        this.$message.warning('此操作只允许选择一条数据');
        return;
      }
      this.globalStartLoad('文件下载中，请稍后...');
      getExcelTemplate({
        id: this.ids
      })
        .then((res) => {
          downloadExcel(res.data, this.selectionList[0].tableName);
        })
        .finally(() => {
          this.globalEndLoad();
        });

      // this.importConfig.fileLoading = true;
      // getExcelTemplate({
      //   id: this.ids
      // })
      //   .then((res) => {
      //     downloadExcel(res.data, this.selectionList[0].tableName);
      //   })
      //   .finally(() => {
      //     this.importConfig.fileLoading = false;
      //   });
    },
    addKeyEvent(keyVal) {
      if (!keyVal) {
        this.$message({
          type: 'warning',
          message: '主键不能为空'
        });
        this.model.primaryKeys = '';
        return;
      }
      let flag = this.model.excelImportPrimaryList.some((item, idx) => {
        return item.primaryKey == keyVal;
      });

      if (flag) {
        this.$message({
          type: 'warning',
          message: '主键已存在'
        });
        return;
      }
      this.model.excelImportPrimaryList.push({
        primaryKey: keyVal
      });
      this.model.primaryKeys = '';
    },

    /**
     * 删除sql
     */
    onHandleDelete() {
      this.$refs.AfterPropertiesCrud.setCurrentRow(null);
      this.dataAfterMap.splice(this.afterIndex, 1);
      this.afterIndex = null;
    },

    onHandleWordDelete() {
      this.$refs.readPropertiesCrud.setCurrentRow(null);
      this.readDataMap.splice(this.wordIndex, 1);
      this.wordIndex = null;
    },

    beforeOpen(done, type) {
      console.log(done, type, 'done, typedone, type');
      if (['edit', 'view'].includes(type)) {
        getDetail(this.form.id).then((res) => {
          this.model = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      debugger;
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.query.parentId = 0;
      this.parentId = 0;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      this.$refs.crud && this.$refs.crud.setCurrentRow(null);
      this.detailData = [];
      this.detailPage.total = 0;
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud && this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.query.parentId = 0;
      this.parentId = 0;
      this.onLoad(this.page, this.query);
      this.$refs.crud && this.$refs.crud.setCurrentRow(null);
      this.detailData = [];
      this.detailPage.total = 0;
    },
    refreshDetailChange() {
      if (!this.parentId) {
        return;
      }
      this.onDetailLoad(this.detailPage, {
        parentId: this.parentId
      });
    },
    handleSelectData(val) {
      let current = 1;
      let pageSize = this.page.pageSize;
      if (val === 'all') {
        // 接口返回上限500条数据
        pageSize = 500;
      } else {
        current = this.page.currentPage;
      }
      this.btnLoading = true;
      getList(current, pageSize, Object.assign({ parentId: 0 }, this.query)).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.exportData = data.records;
        this.btnLoading = false;
      });
    },
    handleExport() {
      this.exportData = this.data;
      this.exprotVisible = true;
    },
    handleClose(val) {
      this.exprotVisible = false;
      this.data = this.exportData.splice(0, this.page.pageSize);
    },
    onLoad(
      page,
      params = {
        parentId: 0
      }
    ) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
        this.$refs.crud && this.$refs.crud.setCurrentRow(null);
      });
    },

    onDetailLoad(page, params = {}) {
      this.detailLoading = true;
      this.query.parentId = params.parentId;
      getList(page.currentPage, page.pageSize, params).then((res) => {
        const data = res.data.data;
        this.detailPage.total = data.total;
        this.detailData = data.records;
        this.detailLoading = false;
        this.selectionClear();
      });
    },

    onClick(row) {
      this.parentId = row.id;
      this.onDetailLoad(this.detailPage, {
        parentId: row.id
      });
    },

    /**
     * 保存
     */
    submit() {
      this.$refs.basicForm.validate(async (valid, done) => {
        if (valid) {
          delete this.model.primaryKeys;
          let paramMap = {
            ...this.model,
            excelImportAfterSqlList: this.dataAfterMap,
            excelImportPrimaryList: this.model.excelImportPrimaryList,
            excelImportFieldList: this.readDataMap
          };
          if (!this.leftTableFlag) {
            paramMap['parentId'] = this.parentId;
          }
          this.globalStartLoad('导入信息中，请稍后...', 'rgba(255,255,255,0.9)');
          add(paramMap).then(
            (res) => {
              if (this.leftTableFlag) {
                this.query.parentId = 0;
                this.detailPage.total = 0;
                this.detailData = [];
                this.onLoad(this.page);
              } else {
                this.onDetailLoad(this.detailPage, {
                  parentId: this.parentId
                });
              }
              setTimeout(() => {
                this.globalEndLoad();
                this.$message({
                  type: 'success',
                  message: `${this.dialogTitle}成功!`
                });
              }, 200);
              this.closeDialog();
            },
            (error) => {
              this.globalEndLoad();
            }
          );
        } else {
          this.tabsIndex = '1';
        }
        done();
      });
    },

    leftSubmitEvent() {},

    /**
     * 保存字段配置
     */
    submitInner() {
      this.$refs.basicInfoForm.validate((valid, done) => {
        if (!valid) return;
        let crtFormInfo = deepClone(this.basicModel);
        if (this.type === 'add') {
          this.readDataMap.push(crtFormInfo);
          this.basicModel = new Object();
        } else {
          this.readDataMap = this.readDataMap.map((item, idx) => {
            if (this.index === idx) {
              item = crtFormInfo;
            }
            return item;
          });
        }
        done();
        // this.$refs.basicInfoForm.resetFields();
        this.$refs.basicInfoForm.resetForm();
        this.fieldDialogConfig.visible = false;
      });
      // this.$refs.readPropertiesCrud.refreshTable();
    },

    // 取消字段配置
    cancelEvent() {
      this.$refs.basicInfoForm.resetFields();
      this.fieldDialogConfig.visible = false;
      // this.basicModel = {}
    },

    clearEvent(idx) {
      this.model.excelImportPrimaryList.splice(idx, 1);
      // this.primaryKeyArr.splice(idx, 1);
    },

    resetForm() {
      this.readDataMap = [];
      this.dataAfterMap = [];
      this.$nextTick(() => {
        this.$refs.basicInfoForm && this.$refs.basicInfoForm.resetForm();
        this.$refs.basicForm && this.$refs.basicForm.resetForm();
      });
    },
    // 读取字段配置 弹窗
    openBasicInfoFormDialog() {
      if (this.type == 'edit') {
        this.$refs.basicInfoForm && this.$refs.basicInfoForm.clearValidate();
        return false;
      } else {
        this.$refs.basicInfoForm && this.$refs.basicInfoForm.resetForm();
        this.$set(this.basicModel, 'getSheetMode', 'NAME');
        this.$set(this.basicModel, 'getColumnMode', 'NAME');
      }
    },
    /**
     * 关闭回调
     */
    closeDialog() {
      this.showDialog = false;
      // this.model = new Object();
      this.basicModel = new Object();
      this.timer = new Date().getTime();
      this.index = null;

      this.$refs.basicForm && this.$refs.basicForm.resetForm();
      this.$set(this.model, 'getSheetMode', 'NAME');
      this.$set(this.model, 'isMultiline', false);
      this.$set(this.model, 'hasTitle', false);
      // 清空type时需要初始化对象复制，如果单纯修改里面属性相当于修改了选中哪行的value值
      // this.type = {
      //   icon: 'el-icon-info',
      //   label: '基础数据',
      //   prop: 'tab1'
      // };
      let arr = Object.keys(this.$refs).filter((k) => k.includes('Form'));
      arr &&
        arr.forEach((item) => {
          if (this.$refs[item] != void 0) {
            this.dialogTitle === '编辑' ? this.$refs[item].resetFields() : this.$refs[item].clearValidate();
          }
        });
    },

    /**
     *监听页面改变
     */
    resetHeightHandler() {
      let t = this;
      window.addEventListener('resize', function () {
        t.resetHeight();
      });
      t.resetHeight();
    },
    /**
     * 减去相应头部的高度得到表格体高度
     */
    resetHeight() {
      // 获取浏览器视图高度除外地址栏高度
      let windowHeight = document.body.clientHeight;
      // 获取最上层功能块高度
      let header = document.getElementsByClassName('avue-header')[0].clientHeight;
      //获取面包屑区域高度
      let avueTags = document.getElementsByClassName('avue-tags')[0].clientHeight;
      // 获取搜索栏高度
      let search = document.getElementsByClassName('avue-crud__search')[0].clientHeight || 0;
      let searchSth = document.getElementsByClassName('avue-crud__search')[1];
      searchSth.setAttribute('style', 'opacity: 0;');
      this.option.height = windowHeight - header - avueTags - search - 200;
      this.detailOption.height = this.option.height;
      this.visible = false;
      this.$nextTick(() => {
        this.visible = true;
      });
    },

    /**
     * 改变tab行切换事件
     */
    handleChange(column) {
      this.type = column;
    }
  }
};
</script>

<style lang="scss" scoped>
.el-dialog__wrapper {
  ::v-deep.el-dialog__body {
    min-height: 60vh;
  }
}
::v-deep .avue-form__group {
  .el-col {
    margin-bottom: 0 !important;
  }
}
.top-title-flex {
  margin-bottom: 10px;
  font-size: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center !important;
}

::v-deep .el-dialog {
  .el-card__body {
    .avue-crud__menu {
      display: none;
    }
  }
}

.el-icon-circle-close {
  float: right;
  line-height: 32px;
}
.detailTable {
  ::v-deep .el-table {
    height: calc(100vh - 366px) !important;
  }
}
::v-deep .el-tabs__item {
  color: #606266 !important;
  font-weight: bold;
}
</style>
<style>
.importConfigDialog .el-upload {
  width: 100%;
}
.importConfigDialog .el-upload-dragger {
  width: 100%;
}
</style>
